<template>
  <div class="hello">
    <h1>新闻</h1>
    <div>
      <ul>
        <li v-for="item in articles">
          <h2>{{item.title}}</h2>
          <img :src="item.images" alt="">
        </li>
      </ul>
    </div>
    <div class="loading">
      loading...
    </div>
    
  </div>
</template>

<script>

  import axios from 'axios';
  export default {
    name: 'News',
    data () {
      return {
        msg: 'Welcome to Your Vue.js App',
        articles:[],
        sw:true
      }
    },
    methods:{
    //vue请求网络接口中图片报错403解决办法
    getImages( _url ){
      if( _url !== undefined ){
        let _u = _url.substring( 7 );
        return 'https://images.weserv.nl/?url=' + _u;
      }
    }
  },
  mounted(){
    // 缓存指针
    let _this = this;
    // 设置一个开关来避免重负请求数据
    _this.sw = true;
    axios.get('/news/latest')
    .then(function(response){
      response.data.stories.map((item)=>{
        //vue请求网络接口中图片报错403
        item.images = _this.getImages(item.images[0])
      })
      _this.articles = response.data.stories;
    })
    .catch(function(error){
      console.log(error);
    });

    // 注册scroll事件并监听
    window.addEventListener('scroll',function(){
      // 滚动高度
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      // console.log(window.innerHeight) //可视区域高度
      // console.log(document.body.offsetHeight); // 文档高度
      // 判断是否滚动到底部
      if(scrollTop + window.innerHeight >= document.body.offsetHeight - 300) {
          // 如果开关打开则加载数据
          if(_this.sw==true){
            // 将开关关闭
            _this.sw = false;
            axios.get('/news/latest')
            .then(function(response){
              response.data.stories.map((item)=>{
                item.images = _this.getImages(item.images[0])
              })
              //合并数组
              _this.articles = [..._this.articles, ...response.data.stories];
              // 数据更新完毕，将开关打开
              _this.sw = true;
            })
            .catch(function(error){
              console.log(error);
            });   
          }
        }
      });
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
li{
  list-style:none;
}
a{
  color: #42b983;
}
</style>
